import React, {useMemo, useRef, useState} from 'react';
import {dataList, ITEM_HEIGHT, VISIBLE_COUNT} from "./constants";


// 每一条的高度
/**
 * 常规虚拟列表
 */
const NormalVirtualList = () => {

	const [startIndex, setStartIndex] = useState(0)
	const scrollTopRef = useRef(0)
	const renderList = useMemo(() => {
		const endIndex = startIndex + VISIBLE_COUNT
		return dataList.slice(startIndex, endIndex)
	}, [startIndex])

	const handleScroll = (e) => {
		const scrollTop = e.target.scrollTop
		const start = Math.floor(scrollTop / ITEM_HEIGHT)
		if(startIndex !== start) {
			setStartIndex(start)
		}
		scrollTopRef.current = scrollTop
	}

	const offsetTop = scrollTopRef.current - (scrollTopRef.current % ITEM_HEIGHT)

	return (
		<div className='virtualListContainer' onScroll={handleScroll}>
			<div className='virtualPhantom' style={{height: dataList.length * ITEM_HEIGHT}}/>
			<div className='virtualContent' style={{transform: `translate3d(0, ${offsetTop}px, 0)`}} >
				{
					renderList.map((item) => (
						<div className='virtualItem' key={item}>你好世界{item}</div>
					))
				}
			</div>
		</div>
		)
}
export default NormalVirtualList

